<?php
namespace User\Model;

use Think\Model;

class FactoryModel extends Model
{
    public static function ajaxImgUpload($img, $model = '')
    {
        $res = array('msg' => "上传失败", 'code' => '-1');
        if (empty($img)) {
            $res['msg'] = '无文件信息';
            return $res;
        }
        // 获取图片
        list($type, $data) = explode(',', $img);
        $ext = '';
        // 判断类型
        if (strstr($type, 'image/png') != '') {
            $ext = '.png';
        } elseif (strstr($type, 'image/gif') != '') {
            $ext = '.gif';
        } elseif (strstr($type, 'image/jpeg') != '') {
            $ext = '.jpg';
        } elseif (strstr($type, 'image/jgp') != '') {
            $ext = '.jpg';
        } else {
            $ext = '.jpg';
        }
        if (empty($ext)) {
            $res['msg'] = '文件类型错误';
            return $res;
        }
        $decoded_data = base64_decode($data);
        $im = @imagecreatefromstring($decoded_data);
        if ($im == false) {
            $res['msg'] = '文件已破坏';
            return $res;
        }
        imagedestroy($im);
        // 生成的文件名
        $dir = "Public/Uploads/" . $model . "/" . date('Ymd');
        if (!is_dir($dir)) mkdir($dir); // 如果不存在则创建
        $save_path = $dir;
        do {
            $name = time() . rand(1, 1000000);
            $save_path = $dir . "/" . $name . $ext;
        } while (file_exists($save_path));
        // 生成文件
        file_put_contents($save_path, base64_decode($data), true);
        // 返回
        header('content-type:application/json;charset=utf-8');
        $res = array('msg' => "/" . $save_path, 'code' => '1');
        return $res;
    }

    //--压缩图片--
    public static function ajaxImgUploadThumb($img, $model = '', $thumb_w = 750)
    {
        $res = array('msg' => "上传失败", 'code' => '-1');
        if (empty($img)) {
            $res['msg'] = '无文件信息';
            return $res;
        }
        // 获取图片
        list($type, $data) = explode(',', $img);
        $ext = '';
        // 判断类型
        if (strstr($type, 'image/jpeg') != '') {
            $ext = '.jpg';
        } elseif (strstr($type, 'image/gif') != '') {
            $ext = '.gif';
        } elseif (strstr($type, 'image/png') != '') {
            $ext = '.png';
        } elseif (strstr($type, 'image/jgp') != '') {
            $ext = '.jpg';
        } else {
            $ext = '.jpg';
        }
        if (empty($ext)) {
            $res['msg'] = '文件类型错误';
            return $res;
        }
        $decoded_data = base64_decode($data);
        $im = @imagecreatefromstring($decoded_data);
        if ($im == false) {
            $res['msg'] = '文件已破坏';
            return $res;
        }
        imagedestroy($im);
        // 生成的文件名
        $dir = "Public/Uploads/" . $model . "/" . date('Ymd');
        if (!is_dir($dir)) mkdir($dir); // 如果不存在则创建
        $save_path = $dir;
        $name = '';
        do {
            $name = time() . rand(1, 1000000);
            $save_path = $dir . "/" . $name . $ext;
        } while (file_exists($save_path));
        // 生成文件
        file_put_contents($save_path, base64_decode($data), true);
        $image = new \Think\Image();
        $image->open($save_path);
        $width = $image->width();
        $thumb_h = $image->height();
        if($width > $thumb_w){
            $width = $width/$thumb_w; //取得图片的长宽比
            $height = $image->height();
            $thumb_h = ceil($height/$width);
        }
        $save_path = $dir . "/thumb" . $name . $ext;
        $image->thumb($thumb_w, $thumb_h)->save($save_path);
        // 返回
        header('content-type:application/json;charset=utf-8');
        $res = array('msg' => "/" . $save_path, 'code' => '1');
        return $res;
    }

    //延迟1秒返回图片路径 (与上面ajaxImgUpload方法不同的是：使用sleep(1))
    public static function delayAjaxImgUpload($img, $model = '')
    {
        $res = array('msg' => "上传失败", 'code' => '-1');
        if (empty($img)) {
            $res['msg'] = '无文件信息';
            return $res;
        }
        // 获取图片
        list($type, $data) = explode(',', $img);
        $ext = '';
        // 判断类型
        if (strstr($type, 'image/png') != '') {
            $ext = '.png';
        } elseif (strstr($type, 'image/gif') != '') {
            $ext = '.gif';
        } elseif (strstr($type, 'image/jpeg') != '') {
            $ext = '.jpg';
        } elseif (strstr($type, 'image/jgp') != '') {
            $ext = '.jpg';
        } else {
            $ext = '.jpg';
        }
        if (empty($ext)) {
            $res['msg'] = '文件类型错误';
            return $res;
        }


        $decoded_data = base64_decode($data);
        $img_len = strlen($decoded_data);
        if($img_len > 400 * 1024){
            $res['msg'] = '文件大于400K，过大';
            return $res;
        }
        $im = @imagecreatefromstring($decoded_data);
        if ($im == false) {
            $res['msg'] = '文件已破坏';
            return $res;
        }
        imagedestroy($im);
        // 生成的文件名
        $dir = "Public/Uploads/" . $model . "/" . date('Ymd');
        if (!is_dir($dir)) mkdir($dir); // 如果不存在则创建
        $save_path = $dir;
        do {
            $name = time() . rand(1, 1000000);
            $save_path = $dir . "/" . $name . $ext;
        } while (file_exists($save_path));
        // 生成文件
        file_put_contents($save_path, base64_decode($data), true);
        // 返回
        sleep(1);
        header('content-type:application/json;charset=utf-8');
        $res = array('msg' => "/" . $save_path, 'code' => '1');
        return $res;
    }

    //调试，写日志文件
    public static function writeLog($path, $data)
    {
        $fp=fopen($path,"a");
        fwrite($fp,$data."\r\n");
        fclose($fp);
    }

    /**
     * 友好的时间显示
     *
     * @param int    $sTime 待显示的时间
     * @param string $type  类型. normal | mohu | full | ymd | other
     * @param string $alt   已失效
     * @return string
     */
    public static function friendlyDate($sTime,$type = 'normal',$alt = 'false') {
        //sTime=源时间，cTime=当前时间，dTime=时间差
        $cTime        =    time();
        $dTime        =    $cTime - $sTime;
        $dDay        =    intval(date("z",$cTime)) - intval(date("z",$sTime));
        //$dDay        =    intval($dTime/3600/24);
        $dYear        =    intval(date("Y",$cTime)) - intval(date("Y",$sTime));
        //normal：n秒前，n分钟前，n小时前，日期
        if($type=='normal'){
            if($dTime == 0){
                return "刚刚";
            }elseif( $dTime < 60 ){
                return $dTime."秒前";
            }elseif( $dTime < 3600 ){
                return intval($dTime/60)."分钟前";
                //今天的数据.年份相同.日期相同.
            }elseif( $dYear==0 && $dDay == 0  ){
                //return intval($dTime/3600)."小时前";
                return '今天'.date('H:i',$sTime);
            }elseif($dYear==0){
                return date("m月d日 H:i",$sTime);
            }else{
                return date("Y-m-d H:i",$sTime);
            }
        }elseif($type=='mohu'){
            if($dTime == 0){
                return "刚刚";
            }elseif( $dTime < 60 ){
                return $dTime."秒前";
            }elseif( $dTime < 3600 ){
                return intval($dTime/60)."分钟前";
            }elseif( $dTime >= 3600 && $dDay == 0  ){
                return intval($dTime/3600)."小时前";
            }elseif( $dDay > 0 && $dDay<=7 ){
                return intval($dDay)."天前";
            }elseif( $dDay > 7 &&  $dDay <= 30 ){
                return intval($dDay/7) . '周前';
            }elseif( $dDay > 30 ){
                return intval($dDay/30) . '个月前';
            }
            //full: Y-m-d , H:i:s
        }elseif($type=='full'){
            return date("Y-m-d , H:i:s",$sTime);
        }elseif($type=='ymd'){
            return date("Y-m-d",$sTime);
        }else{
            if($dTime == 0){
                return "刚刚";
            }elseif( $dTime < 60 ){
                return $dTime."秒前";
            }elseif( $dTime < 3600 ){
                return intval($dTime/60)."分钟前";
            }elseif( $dTime >= 3600 && $dDay == 0  ){
                return intval($dTime/3600)."小时前";
            }elseif($dYear==0){
                return date("Y-m-d H:i:s",$sTime);
            }else{
                return date("Y-m-d H:i:s",$sTime);
            }
        }
    }
    public static function sendMsg($phone, $content)
    {
        $authorization = base64_encode('zbxwfz:' . md5("4lJ#vQ6XxxdoDwHg"));
        $interface = "http://sms.8531.cn/api/v1.0.0/message/send?to=" . $phone . "&content=" .
            urlencode($content) . "&accountId=zbxwfz&authorization=" . $authorization;

        $curl = curl_init();  //初始化
        curl_setopt($curl, CURLOPT_URL, $interface);  //设置url
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);  //设置http验证方法
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  //设置curl_exec获取的信息的返回方式
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    //统计H5等页面的访问量pv、访问人数uv
    public static function viewPage($id)
    {
        $ids = S('h5_view_page_ids');
        if($ids){
            if(!in_array($id, $ids)){
                array_push($ids, $id);
            }
            S('h5_view_page_ids', $ids, 24*60*60);
        }else{
            S('h5_view_page_ids', array($id), 24*60*60);
        }

        $uv = cookie('h5_view_page_cookie_'.$id.date('Y-m-d'));
        $data = array('pv' => 1, 'uv' => 1);
        if($uv){
            $cache = S('h5_view_page_cache_'.$id);
            if($cache){
                $data['pv'] = $cache['pv'] + 1;
                $data['uv'] = $cache['uv'];
            }
        }else{
            $time = strtotime(date('Y-m-d', strtotime('+1 day')).' 00:00:00') - time();
            cookie('h5_view_page_cookie_'.$id.date('Y-m-d'), date('Y-m-d'), $time);
            $cache = S('h5_view_page_cache_'.$id);
            if($cache){
                $data['pv'] = $cache['pv'] + 1;
                $data['uv'] = $cache['uv'] + 1;
            }
        }
        S('h5_view_page_cache_'.$id, $data, 24*60*60);
    }

    //获取模拟人数,basic_number人数基数
    public static function getVirtualNumber($id = 0, $basic_number = 100)
    {
        $number = 0;
        $where['id'] = $id;
        $data = M('data_important')->where($where)->find();
        if(!empty($data)){
            $cache = S('h5_view_page_cache_'.$id);
            $number = $cache ? $cache['pv'] : 0;
            $number = $number + $data['rensheng_view'];
            // 9|sin(x)| + 9x + 100
            $number = 9 * intval(abs(sin($number))) + 9 * $number + $basic_number;
        }
        return $number;
    }
}

?>